<template>
  <div class="container">
    <!-- 查询条件区域 -->
    <div class="query-container">
      <a-form :layout="formLayout" :colon="false">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-form-item label="事件类型">
              <a-select v-model:value="selectedEvent" placeholder="请选择事件类型">
                <a-select-option v-for="event in eventTypes" :key="event" :value="event">
                  {{ event }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="16">
            <a-form-item label="日期范围">
              <a-range-picker
                  v-model:value="dateRange"
                  :disabled-date="disabledDate"
                  placeholder="请选择日期范围"
              />
            </a-form-item>
          </a-col>
          <a-col :span="2">
            <a-form-item>
              <a-button type="primary" icon @click="handleQuery">
                <SearchOutlined />
              </a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮容器 -->
    <div class="button-container">
      <div class="right-buttons">
        <!-- 表格刷新按钮 -->
        <a-button @click="handleRefresh" icon><ReloadOutlined /></a-button>
        <!-- 表格行高修改按钮 -->
        <a-dropdown trigger="click" @visible-change="handleDropdownVisibleChange">
          <a-button icon><ColumnHeightOutlined /></a-button>
          <template #overlay>
            <a-menu @click="handleRowHeightSelect">
              <a-menu-item key="large">大</a-menu-item>
              <a-menu-item key="middle">中</a-menu-item>
              <a-menu-item key="small">小</a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
        <!-- 修改显示列的按钮 -->
        <a-dropdown trigger="click">
          <a-button icon><SettingOutlined /></a-button>
          <template #overlay>
            <a-menu @click="handleColumnChange">
              <a-menu-item-group title="选择显示列">
                <a-draggable v-model:list="visibleColumns" :handle="'.drag-handle'">
                  <a-menu-item
                      v-for="column in columns"
                      :key="column.key"
                      :disabled="column.fixed"
                  >
                    <span class="drag-handle">≡</span>
                    <a-checkbox
                        :checked="visibleColumns.includes(column.key)"
                        @change="(e) => toggleColumnVisibility(column.key, e.target.checked)"
                    >
                      {{ column.title }}
                    </a-checkbox>
                  </a-menu-item>
                </a-draggable>
              </a-menu-item-group>
            </a-menu>
          </template>
        </a-dropdown>
      </div>
    </div>
    <!-- 表格 -->
    <div class="table-container">
      <a-table
          :columns="getVisibleColumns"
          :data-source="filteredData"
          :scroll="{ x: 2000 }"
          :expand-column-width="100"
          :size="tableSize"
      >
        <template #expandedRowRender="{ record }">
          <p style="margin: 0">
            {{ record.description }}
          </p>
        </template>
        <template #expandColumnTitle>
          <span>展开</span>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';
import {
  SettingOutlined,
  ReloadOutlined,
  ColumnHeightOutlined,
  SearchOutlined
} from '@ant-design/icons-vue';
import dayjs from 'dayjs';

// 定义列的类型
type Column = {
  title: string;
  dataIndex: string;
  key: string;
  fixed?: boolean;
};

// 定义数据项的类型
type DataItem = {
  key: string;
  event: string;
  ip: string;
  os: string;
  region: string;
  description: string;
  date: string; // 新增日期字段
};

const columns: Column[] = [
  { title: '事件类型', dataIndex: 'event', key: 'event', fixed: true },
  { title: 'IP', dataIndex: 'ip', key: 'ip' },
  { title: '操作系统', dataIndex: 'os', key: 'os' },
  { title: '地区', dataIndex: 'region', key: 'region' },
  { title: '日期', dataIndex: 'date', key: 'date' }, // 新增日期列
];

const data = ref<DataItem[]>([
  {
    key: '1',
    event: '登录事件',
    ip: '127.0.0.1',
    os: 'windows 11',
    region: '新疆维吾尔自治区',
    description: '这是第一条记录的描述',
    date: '2024-01-01',
  },
  {
    key: '2',
    event: '登录事件',
    ip: '127.0.0.1',
    os: 'windows 11',
    region: '新疆维吾尔自治区',
    description: '这是第二条记录的描述',
    date: '2024-02-01',
  },
  {
    key: '3',
    event: '登录事件',
    ip: '127.0.0.1',
    os: 'windows 11',
    region: '新疆维吾尔自治区',
    description: '这是第三条记录的描述',
    date: '2024-03-01',
  },
]);

// 初始化可见列
const visibleColumns = ref<string[]>(columns.map((column) => column.key));

// 获取可见列
const getVisibleColumns = computed(() => {
  return visibleColumns.value
      .map((key) => columns.find((col) => col.key === key))
      .filter(Boolean) as Column[];
});

// 切换列的可见性
const toggleColumnVisibility = (key: string, isChecked: boolean) => {
  if (isChecked) {
    if (!visibleColumns.value.includes(key)) {
      visibleColumns.value.push(key);
    }
  } else {
    visibleColumns.value = visibleColumns.value.filter((k) => k!== key);
  }
};

// 处理菜单点击事件
const handleColumnChange = (e: any) => {
  e.preventDefault();
};

// 处理表格刷新事件
const handleRefresh = async () => {
  try {
    // 模拟调用 API 获取最新数据
    const newData = await fetchData();
    data.value = newData;
    console.log('表格刷新成功');
  } catch (error) {
    console.error('表格刷新失败:', error);
  }
};

// 模拟调用 API 获取数据
const fetchData = () => {
  return new Promise<DataItem[]>((resolve) => {
    setTimeout(() => {
      resolve([
        {
          key: '4',
          event: '新登录事件',
          ip: '192.168.1.1',
          os: 'Linux',
          region: '广东省',
          description: '这是新记录的描述',
          date: '2024-04-01',
        },
      ]);
    }, 1000);
  });
};

// 表格大小
const tableSize = ref('middle');

// 处理行高选择事件
const handleRowHeightSelect = (e: any) => {
  tableSize.value = e.key;
};

// 处理下拉菜单显示状态变化事件
const handleDropdownVisibleChange = (visible: boolean) => {
  // 可以添加一些额外逻辑，比如记录菜单显示状态等
};

// 查询条件相关
const formLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const eventTypes = ['登录事件', '新登录事件'];
const selectedEvent = ref('');
const dateRange = ref<[dayjs.Dayjs, dayjs.Dayjs] | null>(null);

// 过滤后的表格数据
const filteredData = computed(() => {
  let result = data.value;
  if (selectedEvent.value) {
    result = result.filter((item) => item.event === selectedEvent.value);
  }
  if (dateRange.value) {
    const startDate = dateRange.value[0].format('YYYY-MM-DD');
    const endDate = dateRange.value[1].format('YYYY-MM-DD');
    result = result.filter((item) => {
      return item.date >= startDate && item.date <= endDate;
    });
  }
  return result;
});

// 处理查询事件
const handleQuery = () => {
  // 可以在这里添加额外的查询逻辑，比如发送请求到后端
  console.log('查询条件：', {
    event: selectedEvent.value,
    dateRange: dateRange.value
        ? [dateRange.value[0].format('YYYY-MM-DD'), dateRange.value[1].format('YYYY-MM-DD')]
        : null,
  });
};

// 禁用日期选择
const disabledDate = (current: dayjs.Dayjs) => {
  if (!dateRange.value) {
    return false;
  }
  const start = dateRange.value[0];
  const end = dateRange.value[1];
  if (start &&!end) {
    const maxEnd = start.add(3, 'month');
    return current < start || current > maxEnd;
  }
  return false;
};
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #f9f9f9;
}

.query-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.button-container {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.right-buttons {
  display: flex;
  gap: 10px;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.drag-handle {
  cursor: move;
  margin-right: 8px;
  user-select: none;
}
</style>